﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ABC.Domain.Entities;
using ABC.Domain.Enums;
using RosService.Data;

namespace ABC.Business.Models
{
    public class UserModel
    {
        private readonly RosModel rosModel;
        public UserModel(RosModel rosModel)
        {
            this.rosModel = rosModel;
        }

        public User GetUser(string id)
        {
            var result = new User();
            var user = rosModel.GetEntityById("Пользователь", id, new[]
			                                                        	{
			                                                        		"Имя", "Фамилия", "Отчество", "ЛогинПользователя", "Регион", "Пол", "ТелефонныйНомер",
                                                                            "СсылкаНаОсновнуюРоль", "ВремяСессии", "Email", "РабочаяEmail", "СсылкаНаАватар", "ПарольПользователя", "РазрешитьВход",
                                                                            "ИдентификаторОбъекта"
			                                                        	});
            if (user != null)
            {
                result.Id = id;
                result.Login = user["ЛогинПользователя"].ToString();
                result.FirstName = user["Имя"].ToString();
                result.LastName = user["Фамилия"].ToString();
                result.MiddleName = user["Отчество"].ToString();
                result.Region = user["Регион"].ToString();
                result.TelephoneNumber = user["ТелефонныйНомер"].ToString();
                result.BirthDay = rosModel.GetEntityValue<DateTime>(id, "ДатаРождения");
                result.Sex = user["Пол"].ToString();
                result.Password = user["ПарольПользователя"].ToString();
                result.Avatar = user["СсылкаНаАватар"].ToString();
                result.Email = user["Email"].ToString();
                result.WorkEmail = user["РабочаяEmail"].ToString();
                result.Allowed = (bool)user["РазрешитьВход"];
                result.Role = user["СсылкаНаОсновнуюРоль"].ToString();
                result.TimeOfTheSession = user["ВремяСессии"].ToString();

                if (user["ИдентификаторОбъекта"].ToString().StartsWith("RBS:"))
                    result.IdRBS = Convert.ToInt32(user["ИдентификаторОбъекта"].ToString().Split(':')[1]);
            }
            return result;
        }
        public void UpdateUserInfo(string userId, Dictionary<string, object> values)
        {
            foreach (var value in values)
            {
                rosModel.UpdateEntityValue(userId, value.Key, value.Value);
            }
        }
        public void UpdateUserPassword(string userId, string password)
        {
            rosModel.UpdateEntityValue(userId, "ПарольПользователя", password);
        }

        public void DeleteAvatar(string photoId, string userId)
        {
            rosModel.DeleteEntity(photoId, false);
            rosModel.UpdateEntityValue(userId, "СсылкаНаАватар", "");
        }

        public string SetAvatar(string userId, HttpPostedFileBase data)
        {
            var photoId = rosModel.SaveFile(userId, data);
            rosModel.UpdateEntityValue(userId, "СсылкаНаАватар", Convert.ToDecimal(photoId));
            return photoId.ToString();
        }

        public bool GetNotification(string typeNotification, string userId)
        {
            return rosModel.GetEntityValue<bool>(userId, typeNotification);
        }

        public void SetNotifications(string userId, Dictionary<string, object> values )
        {
            foreach (var value in values)
            {
                rosModel.UpdateEntityValue(userId,value.Key,value.Value);
            }
        }

        public List<SelectListItem> GetListFor(string type)
        {
            switch (type)
            {
                case "phone":
                    return new List<SelectListItem>
                               {
                                   new SelectListItem {Text = "Мобильный", Value = "Мобильный"},
                                   new SelectListItem {Text = "Рабочий", Value = "Рабочий"},
                                   new SelectListItem {Text = "Домашний", Value = "Домашний"}
                               };

                case "im":
                    return new List<SelectListItem>
                        {
                            new SelectListItem {Text = "ICQ", Value = "Icq"},
                            new SelectListItem {Text = "Jabber", Value = "Jabber"},
                            new SelectListItem {Text = "Skype", Value = "Skype"}
                        };
                case "socnet":
                    return new List<SelectListItem>{ new SelectListItem {Text = "Вконтакте", Value = SocialNetworkType.Вконтакте.ToString()}, 
                                                    new SelectListItem {Text = "Одноклассники", Value = SocialNetworkType.Одноклассники .ToString()},
                                                    new SelectListItem {Text = "Мой Мир", Value = SocialNetworkType.МойМир.ToString()},
                                                    new SelectListItem {Text = "Facebook", Value =SocialNetworkType.Facebook.ToString()},
                                                    new SelectListItem {Text = "MySpace", Value = SocialNetworkType.MySpace.ToString()}
                        };
                case "email":
                    return new List<SelectListItem> { new SelectListItem {Text = "Личная", Value = "Личная"}, 
                                                      new SelectListItem {Text = "Рабочая", Value = "Рабочая"}
                        };
                case "address":
                    return new List<SelectListItem>{ new SelectListItem {Text = "Личный", Value = "Личный"}, 
                                                      new SelectListItem {Text = "Рабочий", Value = "Рабочий"}
                        };
                default:
                    return null;
            }
        }

        public List<FieldWithDrop> GetUserPhones(string userId)
        {
            var result = new List<FieldWithDrop>();
            var phone0 = rosModel.GetEntityValue<string>(userId, "ТелефонныйНомер");
            var typePhone0 = rosModel.GetEntityValue<string>(userId, "ТипТелефонныйНомер");
            var field0 = new FieldWithDrop(GetListFor("phone")) { NameField = "PhoneValue0", Value = phone0 };
            field0.ItemList.ForEach(x => { x.Selected = x.Value == typePhone0; });
            field0.IsActive = string.IsNullOrEmpty(phone0) || rosModel.GetEntityValue<bool>(userId, "ТелефонныйНомерАктивен");
            result.Add(field0);
            var count = 1;
            var end = true;
            while (end)
            {
                var phone = rosModel.GetEntityValue<string>(userId, "ТелефонныйНомер" + count);
                var typePhone = rosModel.GetEntityValue<string>(userId, "ТипТелефонныйНомер" + count);
                var isActivePhome = rosModel.GetEntityValue<bool>(userId, "ТелефонныйНомерАктивен" + count);
                if (!string.IsNullOrEmpty(phone))
                {
                    var field = new FieldWithDrop(GetListFor("phone")) { Value = phone, NameField = "PhoneValue" + count, IsActive = isActivePhome };
                    field.ItemList.ForEach(x => { x.Selected = x.Value == typePhone; });
                    result.Add(field);
                    count++;
                }
                else
                {
                    end = false;
                }

            }
            return result;
        }
        public List<FieldWithDrop> GetUserEmails(string userId)
        {
            var result = new List<FieldWithDrop>();
            var email0 = rosModel.GetEntityValue<string>(userId, "Email");
            var typeEmail0 = rosModel.GetEntityValue<string>(userId, "ТипEmail");
            var field0 = new FieldWithDrop(GetListFor("email")) { NameField = "EmailValue0", Value = email0 };
            field0.ItemList.ForEach(x => { x.Selected = x.Value == typeEmail0; });
            field0.IsActive = string.IsNullOrEmpty(email0) || rosModel.GetEntityValue<bool>(userId, "EmailАктивен");
            result.Add(field0);
            var count = 1;
            var end = true;
            while (end)
            {
                var email = rosModel.GetEntityValue<string>(userId, "Email" + count);
                var typeEmail = rosModel.GetEntityValue<string>(userId, "ТипEmail" + count);
                var isActiveEmail = rosModel.GetEntityValue<bool>(userId, "EmailАктивен" + count);
                if (!string.IsNullOrEmpty(email))
                {
                    var field = new FieldWithDrop(GetListFor("email")) { Value = email, NameField = "EmailValue" + count, IsActive = isActiveEmail };
                    field.ItemList.ForEach(x => { x.Selected = x.Value == typeEmail; });
                    result.Add(field);
                    count++;
                }
                else
                {
                    end = false;
                }

            }
            return result;
        }
        public List<FieldWithDrop> GetUserIms(string userId)
        {
            var result = new List<FieldWithDrop>();
            var im0 = rosModel.GetEntityValue<string>(userId, "Im0");
            var typeIm0 = rosModel.GetEntityValue<string>(userId, "ТипIm0");
            var field0 = new FieldWithDrop(GetListFor("im")) { NameField = "ImValue0", Value = im0 };
            field0.ItemList.ForEach(x => { x.Selected = x.Value == typeIm0; });
            result.Add(field0);
            var count = 1;
            var end = true;
            while (end)
            {
                var im = rosModel.GetEntityValue<string>(userId, "Im" + count);
                var typeIm = rosModel.GetEntityValue<string>(userId, "ТипIm" + count);
                if (!string.IsNullOrEmpty(im))
                {
                    var field = new FieldWithDrop(GetListFor("im")) { Value = im, NameField = "ImValue" + count };
                    field.ItemList.ForEach(x => { x.Selected = x.Value == typeIm; });
                    result.Add(field);
                    count++;
                }
                else
                {
                    end = false;
                }

            }
            return result;
        }

        public List<FieldWithDrop> GetUserSocNetworks(string userId)
        {
            var result = new List<FieldWithDrop>();
            var socNet0 = rosModel.GetEntityValue<string>(userId, "СоцСеть0");
            var typeSocNet0 = rosModel.GetEntityValue<string>(userId, "ТипСоцСеть0");
            var field0 = new FieldWithDrop(GetListFor("socnet")) { NameField = "SocNetValue0", Value = socNet0 };
            field0.ItemList.ForEach(x => { x.Selected = x.Value == typeSocNet0; });
            result.Add(field0);
            var count = 1;
            var end = true;
            while (end)
            {
                var socNet = rosModel.GetEntityValue<string>(userId, "СоцСеть" + count);
                var typeSocNet = rosModel.GetEntityValue<string>(userId, "ТипСоцСеть" + count);
                if (!string.IsNullOrEmpty(socNet))
                {
                    var field = new FieldWithDrop(GetListFor("socnet")) { Value = socNet, NameField = "SocNetValue" + count };
                    field.ItemList.ForEach(x => { x.Selected = x.Value == typeSocNet; });
                    result.Add(field);
                    count++;
                }
                else
                {
                    end = false;
                }

            }
            return result;
        }

        public List<Field> GetUserAddresses(string userId)
        {
            var result = new List<Field>();
            var address0 = rosModel.GetEntityValue<string>(userId, "Адрес0");
            var field0 = new Field { NameField = "AddressValue0", Value = address0 };
            result.Add(field0);
            var count = 1;
            var end = true;
            while (end)
            {
                var address = rosModel.GetEntityValue<string>(userId, "Адрес" + count);
                if (!string.IsNullOrEmpty(address))
                {
                    var field = new Field { Value = address, NameField = "AddressValue" + count };
                    result.Add(field);
                    count++;
                }
                else
                {
                    end = false;
                }

            }
            return result;
        }
        public List<FieldWithDrop> GetClientAddresses(string userId)
        {
            var result = new List<FieldWithDrop>();
            var address0 = rosModel.GetEntityValue<string>(userId, "Адрес0");
            var typeAddress0 = rosModel.GetEntityValue<string>(userId, "ТипАдрес0");
            var field0 = new FieldWithDrop(GetListFor("address")) { NameField = "AddressValue0", Value = address0 };
            field0.ItemList.ForEach(x => { x.Selected = x.Value == typeAddress0; });
            result.Add(field0);
            var count = 1;
            var end = true;
            while (end)
            {
                var address = rosModel.GetEntityValue<string>(userId, "Адрес" + count);
                var typeAddress = rosModel.GetEntityValue<string>(userId, "ТипАдрес" + count);
                if (!string.IsNullOrEmpty(address))
                {
                    var field = new FieldWithDrop(GetListFor("address")) { Value = address, NameField = "SocNetValue" + count };
                    field.ItemList.ForEach(x => { x.Selected = x.Value == typeAddress; });
                    result.Add(field);
                    count++;
                }
                else
                {
                    end = false;
                }

            }
            return result;
        }

        public List<NotificationBy> GetContactsUserForNotification(string userId, string field, int startIndex, bool isNullIndex)
        {
            var count = startIndex;
            var result = new List<NotificationBy>();
            var indexes = rosModel.GetEntityValue<string>(userId,
                                                          string.Format("{0}{1}", "СписокДляУведомленийПо", field)).Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            while (true)
            {
                var value = rosModel.GetEntityValue<string>(userId, field + (count == 0 && !isNullIndex ? "" : count.ToString()));
                if (!string.IsNullOrEmpty(value))
                {
                    var index = count;
                    result.Add(new NotificationBy { Value = value, Index = count == 0 && !isNullIndex ? "0" : index.ToString(), IsNotify = indexes.Contains(index.ToString()) });
                    count++;
                }
                else
                {
                    break;
                }

            }
            return result;
        }

        public T GetValue<T>(string id, string field)
        {
            return rosModel.GetEntityValue<T>(id, field);
        }
        public void SetValue(string id, string field, object value)
        {
            rosModel.UpdateEntityValue(id, field, value);
        }

        public bool IsCityPhoneNumber(string phone)
        {
            return (phone.IndexOf("(495)") >= 0 || phone.IndexOf("(499)") >= 0);
        }
    }
}
